/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-10-10 10:45:00
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-10-09 21:56:21
 * @FilePath: \work-tool\my-dev-project\src\views\order\track.tsx
 * @Description: 订单物流追踪页面
 */
import React, { useState } from 'react';
import { Card, Input, Button, Space, Timeline, Descriptions, Empty, Divider, Badge, Select } from 'antd';
import {
  SearchOutlined, TruckOutlined, ShoppingOutlined, HomeOutlined,
  UserOutlined, PhoneOutlined, EnvironmentOutlined,
  ReloadOutlined, DownloadOutlined
} from '@ant-design/icons';

const { Search } = Input;

// 模拟物流追踪数据
const mockTrackingData = {
  orderId: 'ORD-20250901-001',
  status: 'delivered',
  statusText: '已送达',
  orderTime: '2025-09-01 10:30:00',
  payTime: '2025-09-01 10:35:20',
  shipTime: '2025-09-02 08:45:15',
  deliveryTime: '2025-09-03 14:20:30',
  logisticsCompany: '顺丰速运',
  trackingNumber: 'SF1234567890123',
  estimatedDeliveryTime: '2025-09-04 18:00:00',

  // 物流轨迹
  logisticsTrail: [
    {
      time: '2025-09-03 14:20:30',
      location: '北京市朝阳区建国路88号',
      description: '您的订单已由本人签收，感谢您使用我们的服务',
      status: 'delivered'
    },
    {
      time: '2025-09-03 10:15:45',
      location: '北京市朝阳区建国路配送中心',
      description: '快递员[张师傅(13800138001)]正在为您派送',
      status: 'delivering'
    },
    {
      time: '2025-09-03 08:30:22',
      location: '北京市朝阳区分拣中心',
      description: '包裹已到达[北京朝阳分拣中心]',
      status: 'transit'
    },
    {
      time: '2025-09-02 20:12:35',
      location: '北京市海淀区转运中心',
      description: '包裹已到达[北京海淀转运中心]，正在分拣中',
      status: 'transit'
    },
    {
      time: '2025-09-02 08:45:15',
      location: '上海市浦东新区发货中心',
      description: '包裹已出库，开始运输',
      status: 'shipped'
    },
    {
      time: '2025-09-02 06:30:50',
      location: '上海市浦东新区仓库',
      description: '包裹已由仓库打包完成',
      status: 'processing'
    },
    {
      time: '2025-09-01 10:35:20',
      location: '系统',
      description: '订单支付成功，等待仓库发货',
      status: 'paid'
    },
    {
      time: '2025-09-01 10:30:00',
      location: '系统',
      description: '订单已创建',
      status: 'created'
    }
  ],

  // 收货人信息
  recipientInfo: {
    name: '张三',
    phone: '13800138001',
    address: '北京市朝阳区建国路88号',
    zipCode: '100022'
  },

  // 订单商品信息
  orderItems: [
    {
      id: 'P001',
      name: '高级智能手表',
      quantity: 1,
      price: 1299,
      totalPrice: 1299,
      image: 'https://via.placeholder.com/80x80?text=Watch'
    }
  ]
};

// 订单状态配置
const orderStatusConfig = {
  created: { text: '订单创建', color: 'default' },
  paid: { text: '已支付', color: 'blue' },
  processing: { text: '处理中', color: 'purple' },
  shipped: { text: '已发货', color: 'green' },
  delivering: { text: '派送中', color: 'cyan' },
  delivered: { text: '已送达', color: 'success' },
  cancelled: { text: '已取消', color: 'red' },
  returned: { text: '已退货', color: 'magenta' }
};

const OrderTrack: React.FC = () => {
  const [orderId, setOrderId] = useState<string>('ORD-20250901-001');
  // 定义 TrackingData 类型
  type LogisticsTrailItem = {
    time: string;
    location: string;
    description: string;
    status: string;
  };

  type RecipientInfo = {
    name: string;
    phone: string;
    address: string;
    zipCode: string;
  };

  type OrderItem = {
    id: string;
    name: string;
    quantity: number;
    price: number;
    totalPrice: number;
    image: string;
  };

  type TrackingData = {
    orderId: string;
    status: string;
    statusText: string;
    orderTime: string;
    payTime: string;
    shipTime: string;
    deliveryTime: string;
    logisticsCompany: string;
    trackingNumber: string;
    estimatedDeliveryTime: string;
    logisticsTrail: LogisticsTrailItem[];
    recipientInfo: RecipientInfo;
    orderItems: OrderItem[];
  };

  const [trackingData, setTrackingData] = useState<TrackingData>(mockTrackingData);
  const [loading, setLoading] = useState<boolean>(false);
  const [noData, setNoData] = useState<boolean>(false);

  // 搜索订单
  const handleSearch = (value: string) => {
    setOrderId(value);
    searchOrder(value);
  };

  // 刷新数据
  const refreshData = () => {
    searchOrder(orderId);
  };

  // 导出物流信息
  const exportTrackingInfo = () => {
    // 实际项目中这里会调用导出API
    alert('物流信息已导出');
  };

  // 模拟搜索订单
  const searchOrder = (id: string) => {
    setLoading(true);
    setNoData(false);

    // 模拟网络请求延迟
    setTimeout(() => {
      if (id === 'ORD-20250901-001') {
        setTrackingData(mockTrackingData);
      } else if (id === 'notfound') {
        setNoData(true);
      } else {
        // 其他订单ID也返回相同的数据，仅用于演示
        setTrackingData(mockTrackingData);
      }
      setLoading(false);
    }, 800);
  };

  // 获取状态对应的图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'delivered':
        return <HomeOutlined style={{ color: '#52c41a' }} />;
      case 'delivering':
      case 'transit':
        return <TruckOutlined style={{ color: '#1890ff' }} />;
      case 'shipped':
      case 'processing':
        return <ShoppingOutlined style={{ color: '#722ed1' }} />;
      default:
        return <EnvironmentOutlined style={{ color: '#8c8c8c' }} />;
    }
  };

  return (
    <div style={{ padding: 24 }}>
      <Card
        title="订单物流追踪"
        extra={
          <Space>
            <Button
              icon={<ReloadOutlined />}
              onClick={refreshData}
              loading={loading}
            >
              刷新
            </Button>
            <Button
              icon={<DownloadOutlined />}
              onClick={exportTrackingInfo}
            >
              导出
            </Button>
          </Space>
        }
      >
        {/* 搜索区域 */}
        <div style={{ marginBottom: 24 }}>
          <Space>
            <Search
              placeholder="输入订单编号或物流单号"
              allowClear
              enterButton={<SearchOutlined />}
              size="large"
              style={{ width: 400 }}
              defaultValue={orderId}
              onSearch={handleSearch}
            />

            <Select defaultValue="orderId" style={{ width: 120 }}>
              <Select.Option value="orderId">订单编号</Select.Option>
              <Select.Option value="trackingNumber">物流单号</Select.Option>
            </Select>
          </Space>
        </div>

        {loading ? (
          <div style={{ textAlign: 'center', padding: 40 }}>
            <Empty description="正在加载中..." />
          </div>
        ) : noData ? (
          <div style={{ textAlign: 'center', padding: 40 }}>
            <Empty description="未找到相关订单信息" />
          </div>
        ) : (
          <div>
            {/* 订单基本信息 */}
            <Card title="订单基本信息" style={{ marginBottom: 24 }}>
              <Descriptions column={3} bordered>
                <Descriptions.Item label="订单编号">{trackingData.orderId}</Descriptions.Item>
                <Descriptions.Item label="订单状态">
                  <Badge
                    status={orderStatusConfig[trackingData.status]?.color || 'default'}
                    text={orderStatusConfig[trackingData.status]?.text || trackingData.statusText}
                  />
                </Descriptions.Item>
                <Descriptions.Item label="物流公司">{trackingData.logisticsCompany}</Descriptions.Item>
                <Descriptions.Item label="物流单号">{trackingData.trackingNumber}</Descriptions.Item>
                <Descriptions.Item label="下单时间">{trackingData.orderTime}</Descriptions.Item>
                <Descriptions.Item label="支付时间">{trackingData.payTime || '-'}</Descriptions.Item>
                <Descriptions.Item label="发货时间">{trackingData.shipTime || '-'}</Descriptions.Item>
                <Descriptions.Item label="送达时间">{trackingData.deliveryTime || '-'}</Descriptions.Item>
                <Descriptions.Item label="预计送达">{trackingData.estimatedDeliveryTime}</Descriptions.Item>
              </Descriptions>
            </Card>

            {/* 收货人信息 */}
            <Card title="收货人信息" style={{ marginBottom: 24 }}>
              <Descriptions column={3} bordered>
                <Descriptions.Item label="收货人">
                  <Space>
                    <UserOutlined />
                    <span>{trackingData.recipientInfo.name}</span>
                  </Space>
                </Descriptions.Item>
                <Descriptions.Item label="联系电话">
                  <Space>
                    <PhoneOutlined />
                    <span>{trackingData.recipientInfo.phone}</span>
                  </Space>
                </Descriptions.Item>
                <Descriptions.Item label="收货地址" span={3}>
                  <Space>
                    <EnvironmentOutlined />
                    <span>{trackingData.recipientInfo.address}</span>
                  </Space>
                </Descriptions.Item>
              </Descriptions>
            </Card>

            {/* 物流追踪时间线 */}
            <Card title="物流追踪轨迹" style={{ marginBottom: 24 }}>
              <Timeline
                items={trackingData.logisticsTrail.map((item: LogisticsTrailItem, index: number) => ({
                  color: index === 0 ? orderStatusConfig[item.status]?.color : 'default',
                  children: (
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 4 }}>
                        {getStatusIcon(item.status)}
                        <span style={{ marginLeft: 8, fontWeight: 'bold' }}>{item.description}</span>
                      </div>
                      <div style={{ marginLeft: 24, color: '#8c8c8c', fontSize: 12, display: 'flex', justifyContent: 'space-between' }}>
                        <span>{item.location}</span>
                        <span>{item.time}</span>
                      </div>
                    </div>
                  ),
                }))}
              />
            </Card>

            {/* 订单商品信息 */}
            <Card title="订单商品信息">
              <div style={{ display: 'flex', padding: 16, border: '1px solid #f0f0f0', borderRadius: 4 }}>
                <img
                  src={trackingData.orderItems[0]?.image}
                  alt={trackingData.orderItems[0]?.name}
                  style={{ width: 80, height: 80, objectFit: 'cover', marginRight: 16 }}
                />
                <div style={{ flex: 1 }}>
                  <h4 style={{ margin: '0 0 8px 0' }}>{trackingData.orderItems[0]?.name}</h4>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div style={{ color: '#8c8c8c' }}>商品编号：{trackingData.orderItems[0]?.id}</div>
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <span style={{ marginRight: 16 }}>数量：{trackingData.orderItems[0]?.quantity}</span>
                      <span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>¥{trackingData.orderItems[0]?.price.toFixed(2)}</span>
                    </div>
                  </div>
                </div>
              </div>

              <Divider style={{ margin: '16px 0' }} />

              <div style={{ textAlign: 'right', padding: '0 16px 16px 0' }}>
                <div style={{ marginBottom: 8 }}>
                  <span style={{ marginRight: 16 }}>商品总价：</span>
                  <span>¥{trackingData.orderItems.reduce((sum: number, item: OrderItem) => sum + item.totalPrice, 0).toFixed(2)}</span>
                </div>
                <div style={{ marginBottom: 8 }}>
                  <span style={{ marginRight: 16 }}>运费：</span>
                  <span>¥0.00</span>
                </div>
                <div style={{ fontWeight: 'bold', fontSize: 16 }}>
                  <span style={{ marginRight: 16 }}>实付金额：</span>
                  <span style={{ color: '#ff4d4f' }}>¥{trackingData.orderItems.reduce((sum: number, item: OrderItem) => sum + item.totalPrice, 0).toFixed(2)}</span>
                </div>
              </div>
            </Card>
          </div>
        )}
      </Card>
    </div>
  );
};

export default OrderTrack;